package me.zhengjie.modules.weixin.utils;


import me.zhengjie.config.constant.WeChatConstant;
import me.zhengjie.config.exception.WeChatException;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;

/**
 * 类加载工具类
 */
public enum ClazzUtil {
    INSTANCE;

    public Class<?> getAnalyzer(String clzName) throws WeChatException {
        return getReflectClass(WeChatConstant.CLASS_PATH_CORE_ANALYZER, clzName, "Analyzer");
    }

    public Class<?> getProcessor(String clzName) throws WeChatException {
        return getReflectClass(WeChatConstant.CLASS_PATH_CORE_PROCESSOR, clzName, "Processor");
    }

    public Class<?> getReflectClass(String packageName, String clzName, String clzType) throws WeChatException {
        if (StringUtils.isBlank(clzName) || StringUtils.isBlank(clzType)) {
            return null;
        }
        String clazzName = upperFirst(clzName) + upperFirst(clzType);
        String fullClzName = MessageFormat.format(packageName.toLowerCase(), clazzName);
        try {
            Class<?> clazz = Class.forName(fullClzName);

            return !clazz.isInterface() && !clazz.isAnnotation() ? clazz : null;
        } catch (ClassNotFoundException e) {
            throw new WeChatException(clazzName + " 类未实现 或 实现类未定义", e);
        }
    }

    public Class<?> getReflectClass(String clzName) throws WeChatException {
        if (StringUtils.isBlank(clzName)) {
            return null;
        }
        try {
            Class<?> clazz = Class.forName(clzName);

            return !clazz.isInterface() && !clazz.isAnnotation() ? clazz : null;
        } catch (ClassNotFoundException e) {
            throw new WeChatException("getReflectClass 未实现类：" + clzName, e);
        }
    }

    private String upperFirst(String letter) {
        return letter.substring(0, 1).toUpperCase() + letter.substring(1);
    }
}
